<?php 

	/*
	* file: insert.php
	*
	* contents:	insert page. Allows user to insert new documents
	*
	* author: Lisa Pedrazzi, Zanco Federico
	*/



	/*
	* function checkEntry($ctrlName, $field, $table)
	*
	* Input required:	$ctrlName: form control where user inserted the value to check
	*					$field: field where to check value
	*					$table: table where to check value
	*
	* Output:	checks if value posted from $ctrlName is present in ($field, $table). If there's not
	*			such a value then a new entry is created
	*
	* Author: Federico Zanco
	*/

	function checkEntry($ctrlName, $field, $table) {
		global $con;
		
		if ($_POST["$ctrlName"] != "") {
			$query = "SELECT $field FROM $table WHERE $field=\"" . $_POST["$ctrlName"] . "\"";
		
			$res = query($query, $con);
		
			if (mysql_affected_rows($con) == 0 && $ctrlName != "") {
				$query = "INSERT INTO $table (`$field`) VALUES(\"" . $_POST["$ctrlName"] . "\")";
				$res = query($query, $con);
			}
		}
	}



	/*
	* function getNextNum()
	*
	* Input required:	none
	*
	* Output:	return the next valid number to build a key value with from and to values posted
	*
	* Author: Federico Zanco
	*/

	function getNextNum() {
		global $con;
		
		// get the max doc_num value from documents with posted values for from and to fields
		$query = "SELECT MAX(d.doc_num) FROM documents AS d WHERE d.from=\"" . $_POST['from'] . "\" AND d.to=\"" . $_POST['to'] . "\"";
		$res = query($query, $con);
		
		//if any return MAX + 1
		if (mysql_affected_rows($con) > 0) { 
			$max = mysql_fetch_assoc($res);
			if ($max['MAX(d.doc_num)'] !== "") {
				$_POST['doc_num'] = $max['MAX(d.doc_num)'] + 1;
				return $_POST['doc_num'];
			}
		}
		
		//else return 0
		return 0;
	}



	/*
	* function makeDocInsQuery()
	*
	* Input required:	none
	*
	* Output:	make a query to insert values posted from insert form
	*
	* Author: Federico Zanco
	*/

	function makeDocInsQuery() {
		global $docFieldsName, $con;
		
		//get a valid doc_num value to build the key
		$docNum = getNextNum();

		//add non empty fields to query
		
		//doc_num
		$query0 = "INSERT INTO documents (`doc_num`,";
		$query1 = " VALUES(\"$docNum\",";
		
		//description
		if ($_POST['description'] != "") {
			$query0 = $query0."`description`,";
			$query1 = $query1."\"" . $_POST['description'] . "\",";
		}
		
		//expires
		if ($_POST['expires'] != "" && $_POST['expires'] != "N/A") {
			$query0 = $query0."`expires`,";
			$query1 = $query1."\"" . normal2MysqlDate($_POST['expires']) . "\",";	
		}

		//date
		$query0 = $query0."`date`,";
		$query1 = $query1."\"" . normal2MysqlDate($_POST['date']) . "\",";
		
		//binary filename
		$fileName = $_FILES['userfile']['name'];
		$fileName = basename($fileName);
		$size = $_FILES['userfile']['size'];
		$type = $_FILES['userfile']['type'];		
		
		$fp = fopen($_FILES['userfile']['tmp_name'], 'r');
		$content = fread($fp, $size);
		$content = addslashes($content);
		fclose ($fp);
	
		if (!get_magic_quotes_gpc())
			$fileName = addslashes($fileName);
			
		$query0 = $query0 . "`binary`,`filename`,`MIME`,`filesize`,";
		$query1 = $query1 . "\"$content\",\"$fileName\",\"$type\",\"$size\",";
		
		
		//from
		$query0 = $query0."`from`,";
		$query1 = $query1."\"" . $_POST['from'] . "\",";
		
		//to
		$query0 = $query0."`to`,";
		$query1 = $query1."\"" . $_POST['to'] . "\",";
		
		//created_by
		if ($_POST['created_by'] != "") {
			$query0 = $query0."`created_by`,";
			$query1 = $query1."\"" . $_POST['created_by'] . "\",";
		}
		
		//inserted_by
		$query0 = $query0."`inserted_by`,";
		$query1 = $query1."\"" . $_SESSION['username'] . "\",";
		
		//type
		$query0 = $query0."`type`,";
		$query1 = $query1."\"" . $_POST['type'] . "\",";
		
		//department
		$department = $_POST['department'];
				
		$query0 = $query0."`department`,";
		$query1 = $query1."\"$department\",";

		//delete last commas and close brackets
		$query = rtrim ($query0, " ,").") ".rtrim ($query1, " ,").")";
	
		return $query;
	}
	


	//main 
	
	include("init.php");
	
	/* Parameters for the pages */ 
	  
	//Header
	$pageTitle = "Inserimento di un nuovo documento";
	$pageDescription = "Pagina di inserimento di un nuovo documento";
	
	//Content
	$title = "Inserimento di un nuovo documento";
	$errorsText = "";
	
	//if the button Inserisci has been pressed
	if (isset($_POST['Inserisci'])) {
		
		//delete slash in excess
		$_POST['description'] = stripslashes($_POST['description']);
		$_POST['from'] = stripslashes($_POST['from']);
		$_POST['to'] = stripslashes($_POST['to']);
		
		//if user belong to Amministrazione add a POST value for department. It will be used by UI
		if ($_SESSION['department'] != "Amministrazione")
			$_POST['department'] = $_SESSION['department'];
		
		//check if from and to values are new
		checkEntry('from', 'name', 'communication_subjects');
		checkEntry('to', 'name', 'communication_subjects');

		//check inserted values for errors and convert it to a string
		$errorsText = errors2Text(checkErrorsIns());

		//if no errors found
		if ($errorsText == "") {
	
			//make insert query
			$res = query(makeDocInsQuery(), $con);

			//notify the correct result
			$errorsText = "Inserimento effettuato. Il numero di protocollo assegnato al documento ";
			$errorsText = $errorsText . "&egrave;: " . $_POST['from'] . "/" . $_POST['to'] . "/" . $_POST['doc_num'];

			//empty posted values so that thery will be ignored from UI
			$_POST['doc_num'] = "";
			$_POST['description'] = "";
			$_POST['expires'] = "";
			$_POST['date'] = "";
			$_POST['binary'] = "";
			$_POST['from'] = "";
			$_POST['to'] = "";
			$_POST['created_by'] = "";
			$_POST['inserted_by'] = "";
			$_POST['type'] = "";
			$_POST['department'] = "";
		}
	}
	
	$text = showFormDocInsert();
	
	showHeader($pageTitle, $pageDescription);
	showMenu();
	showContents($title, $errorsText, $text);
	showFooter($lastRev);
	
	disconnect($con);
	
?>
